package com.example.zx_springboot.interceptors;



import com.example.zx_springboot.jwt.JWTUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Claims;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;


public class JWTInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Map<String, Object> map = new HashMap<>();
        //获取请求头中令牌
        String token = request.getHeader("token");
        if(!StringUtils.isEmpty(token)) {
            try {
                Claims claims = JWTUtils.parseJwt(token);
                return true;//放行请求
            } catch (RuntimeException e) {
                e.printStackTrace();
                //map.put("msg","密钥错误!");
                map.put("msg", e.getMessage());
            }
        }
        map.put("state",false);//设置状态
        map.put("msg", "没有携带token,token为空");
        //将map 专为json  jackson
        String json = new ObjectMapper().writeValueAsString(map);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(json);
        return false;
    }
}
